package com.jza04.flightbooking.service.impl;

import com.jza04.flightbooking.entity.Ticket;
import com.jza04.flightbooking.mapper.FlightMapper;
import com.jza04.flightbooking.mapper.TicketMapper;
import com.jza04.flightbooking.service.FlightTicketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 航班和机票关联服务实现类
 * 用于解决FlightService和TicketService之间的循环依赖问题
 */
@Service
public class FlightTicketServiceImpl implements FlightTicketService {

    @Autowired
    private FlightMapper flightMapper;
    
    @Autowired
    private TicketMapper ticketMapper;
    
    @Override
    @Transactional
    public boolean decreaseRemainingSeats(String flightId) {
        return flightMapper.decreaseRemainingSeats(flightId) > 0;
    }
    
    @Override
    @Transactional
    public boolean increaseRemainingSeats(String flightId) {
        return flightMapper.increaseRemainingSeats(flightId) > 0;
    }
    
    @Override
    @Transactional
    public boolean cancelTicketsByFlightId(String flightId) {
        List<Ticket> tickets = ticketMapper.findByFlightId(flightId);
        
        if (tickets != null && !tickets.isEmpty()) {
            for (Ticket ticket : tickets) {
                // 先更新票状态为已取消
                ticketMapper.updateStatus(ticket.getTicketId(), "已取消");
                // 然后删除票记录，解除外键约束
                ticketMapper.delete(ticket.getTicketId());
            }
        }
        
        return true;
    }
}